package jwt

import (
	"errors"
	"github.com/fatih/color"
	uuid "github.com/satori/go.uuid"
	"golang.org/x/sync/singleflight"
	"time"

	"github.com/golang-jwt/jwt"
	"github.com/ifnk/micro-blog/internal/pkg/config"
	"github.com/ifnk/micro-blog/internal/pkg/log"
)

func NewJwt(logger *log.Logger, conf *config.Config) *Manager {
	return &Manager{
		SigningKey: []byte(conf.JWT.SigningKey),
		conf:       conf,
	}
}

type Manager struct {
	SigningKey []byte
	conf       *config.Config
}

type UserClaims struct {
	ID uint64 `json:"id"`
	jwt.StandardClaims
}

type BaseClaims struct {
	ID           uint
	Username     string
	NickName     string
	UUID         uuid.UUID
	AuthorityIds []string
}

type CustomClaims struct {
	BaseClaims
	BufferTime int64
	jwt.StandardClaims
}

var (
	//golang防缓存击穿利器--singleflight
	GvaConcurrencyControl = &singleflight.Group{}

	TokenExpired     = errors.New("Token is expired 令牌已过期")
	TokenNotValidYet = errors.New("令牌尚未激活")
	TokenMalformed   = errors.New("That's not even a token 这不是个令牌 ")
	TokenInvalid     = errors.New("Couldn't handle this token:  无法处理此令牌 ")
)

func (j *Manager) CreateClaims(baseClaims BaseClaims) CustomClaims {
	claims := CustomClaims{
		BaseClaims: baseClaims,
		BufferTime: j.conf.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 1000,                   // 签名生效时间
			ExpiresAt: time.Now().Unix() + j.conf.JWT.ExpiresTime, // 过期时间 7天  配置文件
			Issuer:    j.conf.JWT.Issuer,                          // 签名的发行者
		},
	}
	return claims
}

// 创建一个token
func (j *Manager) CreateToken(claims CustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	color.Blue("生成的token 是 token -> %+v", token)
	return token.SignedString(j.SigningKey)
}

// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
func (j *Manager) CreateTokenByOldToken(oldToken string, claims CustomClaims) (string, error) {
	//golang防缓存击穿利器--singleflight
	v, err, _ := GvaConcurrencyControl.Do("JwtManager:"+oldToken, func() (interface{}, error) {
		return j.CreateToken(claims)
	})
	return v.(string), err
}

// 解析 token
func (j *Manager) ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid
	}
}

type User struct {
	Profiles []Profile `gorm:"many2many:user_profiles;foreignKey:Refer;joinForeignKey:UserReferID;References:UserRefer;joinReferences:ProfileRefer"`
	Refer    uint      `gorm:"index:,unique"`
}

type Profile struct {
	Name      string
	UserRefer uint `gorm:"index:,unique"`
}

// Which creates join table: user_profiles
//   foreign key: user_refer_id, reference: users.refer
//   foreign key: profile_refer, reference: profiles.user_refer
